<template>
  <el-dialog
    v-model="visible"
    title="个人资料"
    width="500px"
    :before-close="handleClose"
  >
    <div class="profile-content">
      <!-- 用户头像 -->
      <div class="avatar-section">
        <el-avatar :size="80" class="profile-avatar">
          {{ user.phone?.substr(-4) || 'U' }}
        </el-avatar>
        <div class="avatar-info">
          <h3 class="user-phone">{{ user.phone }}</h3>
          <p class="join-date">注册时间：{{ formatDate(user.createTime) }}</p>
        </div>
      </div>
      
      <!-- 用户信息表单 -->
      <el-form 
        ref="profileFormRef" 
        :model="profileForm" 
        :rules="profileRules" 
        label-width="80px"
        class="profile-form"
      >
        <el-form-item label="手机号">
          <el-input v-model="profileForm.phone" disabled />
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input 
            v-model="profileForm.nickname" 
            placeholder="请输入昵称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="profileForm.email" 
            placeholder="请输入邮箱地址"
            type="email"
          />
        </el-form-item>
        
        <el-form-item label="个人简介">
          <el-input 
            v-model="profileForm.bio" 
            type="textarea"
            placeholder="介绍一下自己..."
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <!-- 统计信息 -->
      <div class="stats-section">
        <h4 class="stats-title">使用统计</h4>
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-number">{{ userStats.totalTodos || 0 }}</div>
            <div class="stat-label">总计任务</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ userStats.completedTodos || 0 }}</div>
            <div class="stat-label">已完成</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ userStats.pendingTodos || 0 }}</div>
            <div class="stat-label">待完成</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ completionRate }}%</div>
            <div class="stat-label">完成率</div>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          :loading="saveLoading"
          @click="handleSave"
        >
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { updateUserProfile, getUserStats } from '../api/user'
import dayjs from 'dayjs'

export default {
  name: 'ProfileDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    user: {
      type: Object,
      required: true
    }
  },
  emits: ['update:modelValue', 'profile-updated'],
  setup(props, { emit }) {
    const profileFormRef = ref()
    const saveLoading = ref(false)
    const userStats = ref({
      totalTodos: 0,
      completedTodos: 0,
      pendingTodos: 0
    })
    
    // 控制对话框显示
    const visible = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    })
    
    // 表单数据
    const profileForm = reactive({
      phone: '',
      nickname: '',
      email: '',
      bio: ''
    })
    
    // 表单验证规则
    const profileRules = {
      nickname: [
        { max: 20, message: '昵称长度不能超过20个字符', trigger: 'blur' }
      ],
      email: [
        { 
          pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, 
          message: '邮箱格式不正确', 
          trigger: 'blur' 
        }
      ]
    }
    
    // 完成率计算
    const completionRate = computed(() => {
      const total = userStats.value.totalTodos
      const completed = userStats.value.completedTodos
      if (total === 0) return 0
      return Math.round((completed / total) * 100)
    })
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '未知'
      return dayjs(dateStr).format('YYYY年MM月DD日')
    }
    
    // 初始化表单数据
    const initFormData = () => {
      profileForm.phone = props.user.phone || ''
      profileForm.nickname = props.user.nickname || ''
      profileForm.email = props.user.email || ''
      profileForm.bio = props.user.bio || ''
    }
    
    // 加载用户统计数据
    const loadUserStats = async () => {
      try {
        const response = await getUserStats()
        if (response.data.code === 200) {
          userStats.value = response.data.data
        }
      } catch (error) {
        console.error('加载用户统计失败:', error)
      }
    }
    
    // 保存个人资料
    const handleSave = async () => {
      if (!profileFormRef.value) return
      
      try {
        await profileFormRef.value.validate()
        
        saveLoading.value = true
        const response = await updateUserProfile(profileForm)
        
        if (response.data.code === 200) {
          ElMessage.success('个人资料更新成功')
          emit('profile-updated', response.data.data)
          visible.value = false
        } else {
          ElMessage.error(response.data.message || '更新失败')
        }
      } catch (error) {
        console.error('更新个人资料失败:', error)
        if (error.response?.data?.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('更新失败')
        }
      } finally {
        saveLoading.value = false
      }
    }
    
    // 关闭对话框
    const handleClose = () => {
      visible.value = false
    }
    
    // 监听对话框打开
    watch(visible, (newValue) => {
      if (newValue) {
        initFormData()
        loadUserStats()
      }
    })
    
    return {
      profileFormRef,
      visible,
      profileForm,
      profileRules,
      saveLoading,
      userStats,
      completionRate,
      formatDate,
      handleSave,
      handleClose
    }
  }
}
</script>

<style scoped>
.profile-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: var(--el-fill-color-extra-light);
  border-radius: 8px;
}

.profile-avatar {
  background: var(--el-color-primary);
  color: white;
  font-weight: 600;
  font-size: 24px;
}

.avatar-info {
  flex: 1;
}

.user-phone {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.join-date {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.profile-form {
  padding: 0 4px;
}

.stats-section {
  padding: 20px;
  background: var(--el-fill-color-extra-light);
  border-radius: 8px;
}

.stats-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.stat-item {
  text-align: center;
  padding: 16px 8px;
  background: var(--el-bg-color);
  border-radius: 6px;
  border: 1px solid var(--el-border-color-lighter);
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: var(--el-color-primary);
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .avatar-section {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .stat-item {
    padding: 12px 6px;
  }
  
  .stat-number {
    font-size: 20px;
  }
}
</style> 